import {HttpException, HttpStatus, Injectable} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreateSysUserDto } from './dto/create-sys_user.dto';
import { UpdateSysUserDto } from './dto/update-sys_user.dto';
import {SysUser} from "./entities/sys_user.entity";

// const crypto = require("crypto")


@Injectable()
export class SysUserService {
  constructor(@InjectRepository(SysUser) private readonly sysUserRepository: Repository<SysUser>,) { }

  async create(createSysUserDto: CreateSysUserDto) {
    const {username, password, phone } = createSysUserDto

    if (!username || !password) {
      return new HttpException('请输入用户名和密码', HttpStatus.BAD_REQUEST)
    }

    const user = await this.sysUserRepository.findOne({where: [{username}, {phone}]})

    if (user) {
      return new HttpException('用户名或手机号已存在', HttpStatus.BAD_REQUEST)
    }
    // TODO 后期进行加密
    return this.sysUserRepository.save(createSysUserDto);
  }

  /**
   * 用户登录
   */
  async login (loginUser: CreateSysUserDto) {
    const {username, password } = loginUser
    const user = await this.sysUserRepository.findOne({
      where: {username}
    })
    // TODO password 解密

    if (!user || !SysUser.comparePassword(password, user.password)){
      return new HttpException('用户名或密码错误', HttpStatus.BAD_REQUEST)
    }
    // if(!user.status){
    //   return new HttpException('用户已锁定，无法登录', HttpStatus.BAD_REQUEST)
    // }
    // 返回登录用用户所需的信息, 权限, 通知, 审核结果等
    // 删除用户敏感信息
    delete user.password
    delete user.salt
    return user
  }

  findAll() {
     return  this.sysUserRepository.find();

  }

  async findOne(id: string) {
    return this.sysUserRepository.findOne({
      where: {
        id,
      }
    });
  }

  update(id: string, updateSysUserDto: UpdateSysUserDto) {
    return this.sysUserRepository.update(id, updateSysUserDto);
  }

  remove(id: string) {
    return this.sysUserRepository.delete(id);
  }

  currentUser(id: string) {


  }

  findAllUserOption() {
    return this.sysUserRepository.find({
      select: ["id", "username", "phone", "realname"]
    })
  }
}
